import RPi.GPIO as g
from time import sleep
import time
import json,socket

configfile="config.json"
cf=open(configfile,"r")
log_conf=json.load(cf)
cf.close()
global devicename
devicename=socket.gethostname()
global lastcount
lastcount=0
if "device" in log_conf:
  devicename=log_conf['device']

g.setmode(g.BCM)
g.setup(1, g.IN,pull_up_down=g.PUD_UP)
global revcount
revcount = []
def increaserev(channel):
	global revcount
	revcount.append(int(time.time()*1000))
	
g.add_event_detect(1, g.RISING, callback=increaserev)
while True:
	sleep(60)
	print "RPM is {0}".format(len(revcount))
	if len(revcount) > 0:
		rc=revcount[:]
		revtime=0
		for i in rc:
			if i > (revtime+100):
				revtime=i
				json_out={"time":  i,"device": devicename,"payload":{"S0":{"timestamp": i,"sensor":"S0","i2c":0,"value":1}}}
				try:
					s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
				except:
					print("{}: could not connect to database".format(time.time()))
				else:
					try:
						s.connect(("banana", 24048))
					except:
						print("{}: could not connect to database".format(time.time()))
					else:
						s.sendall(json.dumps(json_out))
						s.close()
						revcount.remove(i)
			else:
				revcount.remove(i)
#	revcount = 0
